package com.chen.blue.oa.handler;

import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.chen.blue.dictionary.AuditDict;
import com.chen.blue.dictionary.SystemInnerDict;
import com.chen.blue.domain.model.business.*;
import com.chen.blue.domain.model.system.SysDictData;
import com.chen.blue.domain.vo.business.CompetitionVo;
import com.chen.blue.exception.e.DtoNullException;
import com.chen.blue.oa.AbstractOaRequestHandler;
import com.chen.blue.oa.OaRequest;
import com.chen.blue.result.DataResult;
import com.chen.blue.service.security.SecurityService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 校长
 * Created By CLT On 2024/5/29.
 */
@SuppressWarnings("all")
@Slf4j
public class SchoolBossHandler extends AbstractOaRequestHandler {

    public SchoolBossHandler() {
        setRole(SystemInnerDict.ROLE_INNER_SCHOOL_BOSS_CODE);
    }

    @Override
    public Boolean handlerRquest(OaRequest request) throws DtoNullException {

        if (!(request.getRoleCodeList().contains(super.role)))
            return false;

        Long id = request.getId();
        Integer auditStatus = request.getAuditStatus();
        UpdateWrapper<ContestApplyActiveModel> wrapper = new UpdateWrapper<>();

        if (AuditDict.AUDIT_STATUS_PASS.equals(auditStatus)) {

            ContestApplyRecordModel lastVersion = getLastVersion(id);
            setStatusAndVersion(AuditDict.STAGE_STAGE_FIRST, AuditDict.ROLE_INNER_SCHOOL_BOSS_CODE_ID, AuditDict.AUDIT_STATUS_PASS, AuditDict.CURRENT_STATUS_PASS, lastVersion);
            // 第一阶段流程结束，is_active=0
            lastVersion.setIsActive(Boolean.FALSE);
            boolean b1 = iContestApplyRecordService.save(lastVersion);
            if (!b1) {
                log.warn("记录失败");
            } else {
                if (!recordResourceInfoHistory(id, lastVersion)) log.warn("资源记录失败");
            }

            // 审核通过，竞赛表增加记录
            ContestApplyModel contestApplyModel = new ContestApplyModel();
            BeanUtils.copyProperties(iContestApplyActiveService.getById(id), contestApplyModel, ignoreAttribute());
            contestApplyModel.setRelation(id);
            if (iContestApplyService.save(contestApplyModel)) log.warn("竞赛表添加失败");

            // 通过的竞赛表关联相关资源
            ResourceModel resourceModelTemp = null;
            Map<String, Object> wrap = new HashMap<>();
            wrap.put("active_id", id);
            List<ResourceModel> resourceModels = iResourceService.listByMap(wrap);
            List<ResourceModel> tempList = new ArrayList<>();
            for (ResourceModel resourceModel : resourceModels) {
                resourceModelTemp = new ResourceModel();
                BeanUtils.copyProperties(resourceModel, resourceModelTemp, ignoreAttribute());
                resourceModelTemp.setApplyId(contestApplyModel.getId());
                tempList.add(resourceModelTemp);
            }
            iResourceService.updateBatchById(tempList);

            // 通过的赛事加入赛事管理中，后续使用
            List<CompetitionVo> temp = iCompetitionService.competitionListSelect().getResult();
            List<String> competitionName = Objects.nonNull(temp) && !temp.isEmpty() ? temp.stream().map(inner1 -> inner1.getCompetitionName()).collect(Collectors.toList()) : Collections.EMPTY_LIST;

            if (competitionName.contains(contestApplyModel.getEventName())) {
                // 包含赛事，但是可能没有赛项
                for (CompetitionVo competitionVo : temp) {
                    if (competitionVo.getCompetitionName().equals(contestApplyModel.getEventName())) {
                        List<String> itemName = Objects.nonNull(competitionVo.getCompetitionName()) && !competitionVo.getCompetitionItemVos().isEmpty() ? competitionVo.getCompetitionItemVos().stream().map(inner2 -> inner2.getItemName()).collect(Collectors.toList()) : Collections.EMPTY_LIST;
                        if (itemName.contains(contestApplyModel.getCompetitionName())) {
                            // 包含不做任何处理
                        } else {
                            CompetitionItemModel competitionItemModel = new CompetitionItemModel();
                            BeanUtils.copyProperties(contestApplyModel, competitionItemModel, ignoreAttribute());
                            competitionItemModel.setCompetitionId(competitionVo.getId());
                            competitionItemModel.setItemName(contestApplyModel.getCompetitionName());
                            boolean b3 = iCompetitionItemService.save(competitionItemModel);
                            if (!b3) log.warn("赛项添加失败");
                        }
                    }
                }
            } else {
                // 不包含赛事及其赛项
                CompetitionModel competitionModel = new CompetitionModel();
                competitionModel.setCompetitionName(contestApplyModel.getEventName());
                boolean b2 = iCompetitionService.save(competitionModel);
                CompetitionItemModel competitionItemModel = new CompetitionItemModel();
                BeanUtils.copyProperties(contestApplyModel, competitionItemModel, ignoreAttribute());
                competitionItemModel.setCompetitionId(competitionModel.getId());
                competitionItemModel.setItemName(contestApplyModel.getCompetitionName());
                boolean b3 = iCompetitionItemService.save(competitionItemModel);
                if (!(b2 && b3)) log.warn("赛事管理添加失败");
            }


            setUpdateWrapper(wrapper, id, AuditDict.STAGE_STAGE_SECOND, AuditDict.ROLE_INNER_NO, AuditDict.AUDIT_STATUS_NO, AuditDict.CURRENT_STATUS_NOT_REPORT);

            // 防止跨级跨阶段审核
            super.handlerRquest(request);

            return iContestApplyActiveService.update(wrapper);

        } else if (AuditDict.AUDIT_STATUS_NOT_PASS.equals(auditStatus)) {

            ContestApplyRecordModel lastVersion = getLastVersion(id);
            setStatusAndVersion(AuditDict.STAGE_STAGE_FIRST, AuditDict.ROLE_INNER_SCHOOL_BOSS_CODE_ID, AuditDict.AUDIT_STATUS_NOT_PASS, AuditDict.CURRENT_STATUS_NOT_PASS, lastVersion);
            // 停止流程
            lastVersion.setIsActive(Boolean.FALSE);
            boolean b1 = iContestApplyRecordService.save(lastVersion);
            if (!b1) {
                log.warn("记录失败");
            } else {
                if (!recordResourceInfoHistory(id, lastVersion)) log.warn("资源记录失败");
            }

            setUpdateWrapper(wrapper, id, AuditDict.STAGE_STAGE_FIRST, AuditDict.ROLE_INNER_NO, AuditDict.AUDIT_STATUS_NO, AuditDict.CURRENT_STATUS_NOT_REPORT);

            // 防止跨级跨阶段审核
            super.handlerRquest(request);

            return iContestApplyActiveService.update(wrapper);

        }

        return Boolean.FALSE;

    }

    @Override
    public Boolean handlerRequestPersonInfo(OaRequest request) throws DtoNullException {

        if (!(request.getRoleCodeList().contains(super.role)))
            return super.handler.handlerRequestPersonInfo(request);

        Long id = request.getId();
        Integer auditStatus = request.getAuditStatus();
        UpdateWrapper<ContestApplyActiveModel> wrapper = new UpdateWrapper<>();

        if (AuditDict.AUDIT_STATUS_PASS.equals(auditStatus)) {

            ContestApplyRecordModel lastVersion = getLastVersion(id);
            setStatusAndVersion(AuditDict.STAGE_STAGE_SECOND, AuditDict.ROLE_INNER_SCHOOL_BOSS_CODE_ID, AuditDict.AUDIT_STATUS_PASS, AuditDict.CURRENT_STATUS_PASS, lastVersion);
            // 第二阶段流程结束，is_active=0
            lastVersion.setIsActive(Boolean.FALSE);
            boolean b1 = iContestApplyRecordService.save(lastVersion);
            if (!b1) {
                log.warn("记录失败");
            } else {
                // 记录历史人员信息
                if (!recordPersonInfoHistory(id, lastVersion)) log.warn("记录历史人员信息失败");
            }

            setUpdateWrapper(wrapper, id, AuditDict.STAGE_STAGE_THIRD, AuditDict.ROLE_INNER_NO, AuditDict.AUDIT_STATUS_NO, AuditDict.CURRENT_STATUS_NOT_REPORT);

            // 防止跨级跨阶段审核
            super.handlerRequestPersonInfo(request);

            return iContestApplyActiveService.update(wrapper);

        } else if (AuditDict.AUDIT_STATUS_NOT_PASS.equals(auditStatus)) {

            ContestApplyRecordModel lastVersion = getLastVersion(id);
            setStatusAndVersion(AuditDict.STAGE_STAGE_SECOND, AuditDict.ROLE_INNER_SCHOOL_BOSS_CODE_ID, AuditDict.AUDIT_STATUS_NOT_PASS, AuditDict.CURRENT_STATUS_NOT_PASS, lastVersion);
            // 停止流程
            lastVersion.setIsActive(Boolean.FALSE);
            boolean b1 = iContestApplyRecordService.save(lastVersion);
            if (!b1) {
                log.warn("记录失败");
            } else {
                // 记录历史人员信息
                if (!recordPersonInfoHistory(id, lastVersion)) log.warn("记录历史人员信息失败");
            }

            setUpdateWrapper(wrapper, id, AuditDict.STAGE_STAGE_SECOND, AuditDict.ROLE_INNER_NO, AuditDict.AUDIT_STATUS_NO, AuditDict.CURRENT_STATUS_NOT_REPORT);

            // 防止跨级跨阶段审核
            super.handlerRequestPersonInfo(request);

            return iContestApplyActiveService.update(wrapper);

        }

        return Boolean.FALSE;

    }

    @Override
    public Boolean handlerRequestContestResult(OaRequest request) throws DtoNullException {

        if (!(request.getRoleCodeList().contains(super.role)))
            return super.handler.handlerRequestContestResult(request);

        Long id = request.getId();
        Integer auditStatus = request.getAuditStatus();
        UpdateWrapper<ContestApplyActiveModel> wrapper = new UpdateWrapper<>();

        if (AuditDict.AUDIT_STATUS_PASS.equals(auditStatus)) {

            ContestApplyRecordModel lastVersion = getLastVersion(id);
            setStatusAndVersion(AuditDict.STAGE_STAGE_THIRD, AuditDict.ROLE_INNER_SCHOOL_BOSS_CODE_ID, AuditDict.AUDIT_STATUS_PASS, AuditDict.CURRENT_STATUS_PASS, lastVersion);
            // 第三阶段流程结束，is_active=0
            lastVersion.setIsActive(Boolean.FALSE);
            lastVersion.setEndTime(new Date());
            boolean b1 = iContestApplyRecordService.save(lastVersion);
            if (!b1) {
                log.warn("记录失败");
            } else {
                // 记录历史结果信息
                if (!recordResultInfoHistory(id, lastVersion)) log.warn("记录历史结果信息失败");
            }

            // 流程结束，删除活动表和竞赛表
            Map<String, Object> wrapperVar1 = new HashMap<>();
            wrapperVar1.put("relation", id);

            // 防止跨级跨阶段审核
            super.handlerRequestContestResult(request);

            return iContestApplyActiveService.removeById(id) && iContestApplyService.removeByMap(wrapperVar1);

        } else if (AuditDict.AUDIT_STATUS_NOT_PASS.equals(auditStatus)) {

            ContestApplyRecordModel lastVersion = getLastVersion(id);
            setStatusAndVersion(AuditDict.STAGE_STAGE_THIRD, AuditDict.ROLE_INNER_SCHOOL_BOSS_CODE_ID, AuditDict.AUDIT_STATUS_NOT_PASS, AuditDict.CURRENT_STATUS_NOT_PASS, lastVersion);
            // 停止流程
            lastVersion.setIsActive(Boolean.FALSE);
            boolean b1 = iContestApplyRecordService.save(lastVersion);
            if (!b1) {
                log.warn("记录失败");
            } else {
                // 记录历史结果信息
                if (!recordResultInfoHistory(id, lastVersion)) log.warn("记录历史结果信息失败");
            }

            setUpdateWrapper(wrapper, id, AuditDict.STAGE_STAGE_THIRD, AuditDict.ROLE_INNER_NO, AuditDict.AUDIT_STATUS_NO, AuditDict.CURRENT_STATUS_NOT_REPORT);

            // 防止跨级跨阶段审核
            super.handlerRequestContestResult(request);

            return iContestApplyActiveService.update(wrapper);

        }


        return Boolean.FALSE;

    }

}
